<!-- 定义表单 表单中有表单项 表单需要绑定对象， 表单项需要绑定对象的成员变量 提交表单需要使用ajax方法提交json对象 -->
<!-- el-cascader 级联下拉选择框 需要通过options指定选项，这里绑定了options变量所以需要自己在data定义options 变量 绑定了change事件（当用户选择性的选项时候激活 handleChange，将多级选择的地址值组合 赋值给指定对象的属性）并且选中的值绑定给
selectedOptions
-->
<template>
  <div class="content">
    <el-dialog title="新增用戶" :visible.sync="editDialogIsShow" :before-close="handleClose" :close-on-click-modal="false">
      <el-form   label-width="100px"  ref="editCourseUploadForm" class="imgUploadForm" style="position: absolute;top: 300px;">
        <!-- 代码中的1表示第几个 和引入js的type变量对应 -->
        <!-- action 就是原来普通form action也就是提交地址 所以对应方法返回后端正确的action请求地址-->
        <el-form-item label="课程图片:"  style="margin-left: 0px;">
          <el-upload
            class="upload"
            :action="getUploadUrl"
            list-type="picture-card"
            :limit="limitNum"
            accept="image/*"
            :on-change="(file,fileList)=>{imgHandleChange(file,fileList,1,this,'editCourseUploadForm','course')}"
            :on-remove="(file,fileList)=>{imgHandleRemove(1,this,file)}"
            :on-before="(file,fileList)=>{imghandleBeforeUpload(file,1,this)}"
            :auto-upload="false"
            :file-list="fileList"
            ref="file1">
            <i class="el-icon-plus"></i>
          </el-upload>
          <!--<viewer-dialog ref="viewer" :images="imagesUp"></viewer-dialog>-->
        </el-form-item>
      </el-form>
      <el-form :model="course" :rules="editCourseRules" ref="editCourseForm">

        <el-form-item  label="课程号：" label-width="100px" prop="cno">
          <el-col :span="16">
            <el-input v-model="course.cno" placeholder="请填入课程号"/>
          </el-col>
        </el-form-item>

        <el-form-item  label="课程名称：" label-width="100px" prop="cname">
          <el-col :span="16">
            <el-input v-model="course.cname" placeholder="请填入课程名"/>
          </el-col>
        </el-form-item>


        <el-form-item  label="开设学期：" label-width="100px">
          <el-col :span="16">
            <el-input v-model="course.grade" placeholder="请填入学期"/>
          </el-col>
        </el-form-item>

        <div style="width:200px;height:200px;">

        </div>

        <el-form-item  label="课程简介：" label-width="100px" >
          <el-col :span="16">
            <el-input
              type="textarea"
              :rows="2"
              placeholder="请输入内容"
              v-model="course.cdesc">
            </el-input>
          </el-col>
        </el-form-item>




        <el-row>
          <el-col :span="16">
            <span class="editSpan">&nbsp;</span>
          </el-col>
          <el-col :span="8">
            <el-button type="primary" @click="editCourse">添加课程</el-button>
          </el-col>
        </el-row>
      </el-form>
    </el-dialog>
  </div>
</template>

<script>
  import api from "../../../../axios/api.js"
  import utils from "../../../../static/js/utils/upload.js"
  import $ from 'jquery'
  export default {
    props:["editDialogIsShow"],
    name: "edit",
    data(){
      return {
        course:{"imgs":""},//增加的时候需要说明要操作的成员变量避免出现undefined
        //校验
        editCourseRules: {
          cno: [
            {required: true, message: "学号不能为空", trigger: 'blur'},
            {validator: this.validateLength, trigger: 'blur'}
          ],
          cname: [{required: true, message: "姓名不能为空", trigger: 'blur'}]
        },
        //校验结束
        //上传使用
        fileList: [], //缓存区文件
        uploadFile:[], //  上传用文件
        formData:{files:[]},
        imagesUp:null,
        //上传使用结束
        test:true,
        limitNum:3
      }
    },
    methods:{
      editCourse:function () {
        this.$refs['editCourseForm'].validate(valid => {//此处refs对象和标签上的ref对应
          if (valid) {

            api.setDataFromAxios("/api/TestWeb/courseController/editCourse", this.course, "post", null).then(
              dto => {
                this.$message.success("学生信息修改成功");
                this.handleClose();
              }
            )
          } else {
            this.$message.warning("请正确格式填写后提交");
            return
          }
        })
      },

      //根据id查询学生信息
      getCourseByCno:function(){
        let _this = this;
        api.setDataFromAxios("/api/TestWeb/courseController/getCourseById/"+this.course.cno,null,"get",null).then(
          dto=>{
            console.log(dto);
            _this.course = dto.t;
            console.log("----------99------------");
            console.log(_this.course);
            //处理图片字段的地址 变成对应的file 对象 el-upload才能匹配显示
            if(this.course.imgs!=null&&this.course.imgs!=''){
              this.oldImg = true;
              let urls = this.course.imgs.split(",");

              for (var i=0;i<urls.length;i++) {
                let fileObj = {};
                fileObj.name="file";
                fileObj.url = "http://UHZCMXBH6U8INJR:8080/upload/course/" + urls[i];
                //this.fileList[i] = fileObj;
                this.fileList.push(fileObj);
                console.log(this.fileList);
              }

            }
          }
        )
      },
      initEditCourse(course){//谁调用谁赋值，父组件被点击的那一行提供
        this.course = course;//
        console.log("---------77777--------------");
        console.log(course);
        this.getCourseByCno();


      },


      //提供给change事件刷新输入
      updateView(e) {
        this.$forceUpdate();
      },
      handleClose:function(){
        //给父组件传参
        this.$emit("closeEditDialog");
      },
      //多文件上传
      imghandleBeforeUpload(file,type,vm) {
        return utils.UPLOAD.Upload().handleBeforeUpload(file,type,vm);
      },
      imgHandleChange(file, fileList, type,vm,modelName,name) {
        // if(vm.fileList.length!=0){
        //   alert("请先删除再提交")
        //   return
        // }
        return utils.UPLOAD.Upload().handleChange(file, fileList, type,vm,modelName,name);
      },
      imgHandleRemove(type,vm,file) {

        let index =  utils.UPLOAD.Upload().handleRemove( type,vm,file);
        $(".el-upload--picture-card").css("display","inline-block");
        alert(index);
        console.log("----------777--------------");
        this.course.imgs = utils.UPLOAD.Upload().delStringByIndex(this.course.imgs,index);
        console.log(this.course.imgs);

        return index>0?true:false;
      },
      uploadImg:function(modelName,name,file){
        //  使用formdata格式
        let formData = new FormData();//准备一个空的表单对象
        formData.append("model",modelName);//图片上传子目录名放入表单对象
        if (this.formData.files[name]) {
          formData.append("file", this.formData.files[name]);//文件放入表单对象
        }
        //为什么要封装一下方法 1.每个vue组件有自己的一些参数处理，简化调用本来这个setDataFromAxios这个方法属于api 重新封装就属于当前页面
        api.setDataFromAxios("/api/TestWeb/uploadController/upload",formData,"post",{headers: { "Content-Type": "multipart/form-data" }})
          .then(dto=>{
            if(dto.code==200){
              this.$message.success (dto.msg);
              if (this.course.imgs==''){
                this.course.imgs = dto.tList[0];//第一次增加特殊处理
              }else {
                this.course.imgs = this.course.imgs + "," + dto.tList[0];
              }
              this.fileList.push(file);
              if (this.fileList.length==this.limitNum){
                $(".el-upload--picture-card").css("display","none");
              }
              console.log(this.course.imgs);
            }else{
              this.$message.error (dto.msg);
            }
          });//.then方法 就是当服务器有返回的时候执行回调函数，对比jquery的ajax success:function（data）
      },
      //多文件上传结束
    },
    created() {
    },
    computed:{
      getUploadUrl(){
        return      "/api/TestWeb/uploadController/upload";
      }
    },
  }
</script>

<style scoped lang="stylus">
  .content
    position relative
  /deep/ .el-form-item__content
    margin-left 0px;
</style>
